/*  
  -- The Lime II Project -- 

  A tuplespaces-based middleware for coordinating agents and mobile hosts.
  Copyright (C) 2005.
  Gian Pietro Picco, Amy L. Murphy, Lorenzo Bellini.

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Lesser General Public License for more details.

  You should have received this copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
 */

package test;

import java.net.InetAddress;

import lime2.LimeServerID;
import lime2.Location;
import lime2.TupleID;
import sagroup.dracots.DracoTS;
import sagroup.dracots.ShareTuple;
import sagroup.dracots.policy.RPTuple;
import sagroup.dracots.policy.ReplicationPolicy;
import sagroup.dracots.TupleType;

/**
 * A simple agent performing some basic operation.<br>
 * 
 * @author Zhang Jinxue
 */

public class ReadReplicaAgent implements Runnable {

	/**
	 * Run method.
	 */
	public void run() {
		System.out.println("ReadReplica Agent started");
		try {
			DracoTS dts = DracoTS.get("testing");
			String type = "type";

			// set the replica policy for type
			ReplicationPolicy rPolicy = new ReplicationPolicy(((byte) 3)); 
			System.out.println("Apply " +rPolicy+ " policy for type "+ type);
			RPTuple policy = new RPTuple(new TupleType(type), rPolicy);
			dts.out(policy);
			
			// Read the tuple by template
			LimeServerID remoteID = new LimeServerID(InetAddress.getLocalHost(), 30000);
			for (int j = 1; j <= 10; j++){
				if(j == 4){
					Thread.sleep(6000);
					System.out.println("The tuple may be deleted by remote host");
				}
				
				for(int i = 1; i < 10; i ++){
					TupleID vid = new TupleID(remoteID, i);
					ShareTuple template = ShareTuple.createVIDTemplate(vid);
					template.setCurr(new Location(remoteID));
					template.setDest(new Location(remoteID));
					ShareTuple ret = (ShareTuple)dts.rdp(template);
					if(ret != null)
						System.out.println("ReadReplicaAgent has read tuple with vid: " + ret.getVID() 
								+ " Version: " + ret.getVer()
								+ " is replica? " + ((ShareTuple)ret).isReplica() 
								);
					else
						System.out.println("The tuple has beed deleted!");
					if(j == 1 && i == 1)
						Thread.sleep(1000);
				}
			}
			
			System.out.println("ReadReplica Agent done!");
		} catch (Exception e) {
			System.out.println("Operation failed!");
			e.printStackTrace();
		}
	}
}